/**
 * @description 内容脚本，负责页面文本处理和翻译展示
 * @author LingXiYi
 */

// 当前页面的翻译状态
let translationEnabled = false;
let currentTargetLang = 'zh';

// 存储原始文本
const originalTexts = new WeakMap();

/**
 * @description 初始化页面翻译功能
 */
async function initializeTranslation() {
  // 获取保存的设置
  const { enabled, targetLang } = await chrome.storage.local.get(['enabled', 'targetLang']);
  translationEnabled = enabled;
  currentTargetLang = targetLang;

  if (translationEnabled) {
    translatePage();
  }

  // 监听来自popup的消息
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'toggleTranslation') {
      translationEnabled = request.enabled;
      currentTargetLang = request.targetLang;
      
      if (translationEnabled) {
        translatePage();
      } else {
        restoreOriginalText();
      }
      sendResponse({ success: true });
    }
  });
}

/**
 * @description 将文本分段
 * @param {string} text - 待分段的文本
 * @param {number} maxLength - 每段最大长度
 * @returns {Array<string>} 分段后的文本数组
 */
function splitText(text, maxLength = 5000) {
  const segments = [];
  let start = 0;
  
  while (start < text.length) {
    let end = start + maxLength;
    
    if (end < text.length) {
      const lastPeriod = text.lastIndexOf('。', end);
      const lastQuestion = text.lastIndexOf('？', end);
      const lastExclamation = text.lastIndexOf('！', end);
      const lastComma = text.lastIndexOf('，', end);
      const lastDot = text.lastIndexOf('.', end);
      
      end = Math.max(
        lastPeriod !== -1 ? lastPeriod + 1 : 0,
        lastQuestion !== -1 ? lastQuestion + 1 : 0,
        lastExclamation !== -1 ? lastExclamation + 1 : 0,
        lastComma !== -1 ? lastComma + 1 : 0,
        lastDot !== -1 ? lastDot + 1 : 0
      );
      
      if (end <= start) {
        end = start + maxLength;
      }
    }
    
    segments.push(text.slice(start, end));
    start = end;
  }
  
  return segments;
}

/**
 * @description 批量翻译文本
 * @param {Array<string>} segments - 文本段落数组
 * @param {string} targetLang - 目标语言
 * @returns {Promise<Array<string>>} 翻译结果数组
 */
async function batchTranslate(segments, targetLang) {
  // 将segments分组，每组5个段落
  const batchSize = 5;
  const batches = [];
  for (let i = 0; i < segments.length; i += batchSize) {
    batches.push(segments.slice(i, i + batchSize));
  }
  
  let results = [];
  for (const batch of batches) {
    // 并发翻译每个批次中的段落
    const batchResults = await Promise.all(
      batch.map(segment =>
        chrome.runtime.sendMessage({
          type: 'translate',
          text: segment,
          targetLang: targetLang
        })
      )
    );
    
    results = results.concat(batchResults);
    // 每个批次之间稍作延迟
    await new Promise(resolve => setTimeout(resolve, 50));
  }
  
  return results;
}

/**
 * @description 判断是否需要翻译的内容
 * @param {Node} node - 文本节点
 * @returns {boolean} 是否需要翻译
 */
function shouldTranslate(node) {
  const text = node.textContent.trim();
  if (!text || text.length < 2) return false;
  
  const parent = node.parentElement;
  if (!parent) return false;
  
  // 排除不需要翻译的元素
  const excludeTags = ['SCRIPT', 'STYLE', 'CODE', 'PRE', 'TEXTAREA'];
  if (excludeTags.includes(parent.tagName)) return false;
  
  // 排除导航栏、按钮等UI元素
  const excludeClasses = ['nav', 'menu', 'button', 'btn'];
  if (excludeClasses.some(cls => parent.className.toLowerCase().includes(cls))) return false;
  
  return true;
}

/**
 * @description 翻译页面内容
 */
async function translatePage() {
  const textNodes = Array.from(getTextNodes(document.body))
    .filter(shouldTranslate);
  
  // 按段落分组处理
  const paragraphs = new Map();
  for (const node of textNodes) {
    if (!originalTexts.has(node)) {
      originalTexts.set(node, node.textContent);
    }
    
    const text = node.textContent.trim();
    if (text) {
      const segments = splitText(text);
      paragraphs.set(node, segments);
    }
  }
  
  // 批量翻译所有段落
  for (const [node, segments] of paragraphs) {
    try {
      const results = await batchTranslate(segments, currentTargetLang);
      let translatedText = '';
      
      for (let i = 0; i < results.length; i++) {
        const result = results[i];
        if (result && !result.error) {
          translatedText += result.translatedText;
        } else {
          console.error('翻译段落失败:', segments[i]);
        }
      }
      
      if (translatedText) {
        node.textContent = translatedText;
      }
    } catch (error) {
      console.error('翻译错误:', error);
    }
  }
}

/**
 * @description 获取页面中的所有文本节点
 * @param {Node} node - 起始节点
 * @returns {Array<Node>} 文本节点数组
 */
function getTextNodes(node) {
  const textNodes = [];
  const walk = document.createTreeWalker(
    node,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode: function(node) {
        // 排除脚本和样式标签中的文本
        const parent = node.parentElement;
        if (parent && (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE')) {
          return NodeFilter.FILTER_REJECT;
        }
        return node.textContent.trim() ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
      }
    }
  );
  
  let currentNode;
  while (currentNode = walk.nextNode()) {
    textNodes.push(currentNode);
  }
  
  return textNodes;
}

/**
 * @description 恢复页面原始文本
 */
function restoreOriginalText() {
  const textNodes = getTextNodes(document.body);
  
  for (const node of textNodes) {
    if (originalTexts.has(node)) {
      node.textContent = originalTexts.get(node);
    }
  }
}

// 初始化翻译功能
initializeTranslation(); 